import axios from 'axios'
import serviceConfig from './config';
import { Message } from 'element-ui'

//创建axios实例
const service = axios.create({
  baseURL: serviceConfig.baseURL,
  timeout: 2000
})

//请求拦截器
service.interceptors.request.use(
  //返回连个回调函数，一个成功，一个失败
  (config) => {
    console.log('请求配置', config);
    return config
  },
  (error) => {
    //请求通常是通过异步去处理，所以返回一个promise
    Promise.reject(error)
  }
)

//响应拦截器
service.interceptors.response.use(
  (res) => {
    console.log('响应结果',res);
  },
  //返回错误信息，错误状态码
  (error) => {
    console.log(error);
    let message = ''
    if(error && error.response){
      switch (error.response.status){
        case 400:
          Message.info = '请求错误'
          break
        case 401:
          break
        case 402:
          break
        case 403:
          Message.info = '身份已失效，请重新登录'
          break
        case 404:
          Message.info = `请求地址出错: ${error.response.config.url}`
          break
        case 408:
          Message.info = '请求超时'
          break
        case 500:
          Message.info = '服务器内部错误'
          break
        case 501:
          Message.info = '服务未实现'
          break
        case 502:
          Message.info = '网关错误'
          break
        case 503:
          Message.info = '服务不可用'
          break
        case 504:
          Message.info = '网关超时'
          break
        case 505:
          Message.info = 'HTTP版本不受支持'
          break
        default:
          break
      }
    }
    return Promise.reject(error)
  }
)
export default service